package com.wct.permission.security;

import org.springframework.security.core.AuthenticationException;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author WEI (Email:changtan20000@163.com)
 * @description
 * @date 2020/2/11 14:57
 */
public class ImageCodeAuthenticationFilter extends OncePerRequestFilter {

    private MyAuthenticationFailureHandler authenticationFailureHandler;

    public void setAuthenticationFailureHandler(MyAuthenticationFailureHandler authenticationFailureHandler) {
        this.authenticationFailureHandler = authenticationFailureHandler;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 判断当前请求，是否为登录请求
        if (request.getRequestURI().contains("/login")) {
            // 校验验证码
            try {
                // 获取用户输入的验证码
                String imageCode = request.getParameter("imageCode");
                if (StringUtils.isEmpty(imageCode.trim())) {
                    throw new ImageCodeException("验证码必须输入");
                }

                // 获取系统生成的验证码
                String key = (String) request.getSession().getAttribute("verificationCode");

                // 把验证码转换成大写
                imageCode = imageCode.toUpperCase();
                key = key.toUpperCase();
                if (!key.equals(imageCode.trim())){
                    throw new ImageCodeException("验证码不一致");
                }
            } catch (AuthenticationException e) {
                authenticationFailureHandler.onAuthenticationFailure(request,response, e);
                return;
            }
        }

        filterChain.doFilter(request, response);
    }
}
